package ce51.dunghn.imagethread;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import vg.com.chatonline.activity.R;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import ce51.dunghn.imagethread.Constants.Extra;

import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.PauseOnScrollListener;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

public class GVActivity extends BaseActivity {
	ArrayList<HashMap<String, String>> imagelist = new ArrayList<HashMap<String, String>>();
	String[] imageUrls;
	DisplayImageOptions options;
	String url = "http://android.dzanchoi.vn/api/images/list.xmob?id=";
	int page = 16;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		setContentView(R.layout.gridview);
		imagelist = loadImage(page);
		imagelist.addAll(loadImage(page + 1));
		imagelist.addAll(loadImage(page + 2));
		HashMap<String, String> hm = new HashMap<String, String>();
		imageUrls = new String[imagelist.size()];
		for (int i = 0; i < imagelist.size(); i++) {
			hm = imagelist.get(i);
			imageUrls[i] = hm.get("images");
		}

		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.stub_image)
				.showImageForEmptyUri(R.drawable.image_for_empty_url)
				.cacheInMemory().cacheOnDisc()
				.bitmapConfig(Bitmap.Config.RGB_565).build();

		GridView gridView = (GridView) findViewById(R.id.gridview);
		gridView.setAdapter(new ImageAdapter());
		gridView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				startImageGalleryActivity(position);
			}
		});
		gridView.setOnScrollListener(new PauseOnScrollListener(true, true));
	}

	// Mo activity moi
	private void startImageGalleryActivity(int position) {
		Intent intent = new Intent(this, ImagePagerActivity.class);
		intent.putExtra(Extra.IMAGES, imageUrls);
		intent.putExtra(Extra.IMAGE_POSITION, position);
		startActivity(intent);
	}

	// Load data tu json
	public ArrayList<HashMap<String, String>> loadImage(int page) {
		ArrayList<HashMap<String, String>> imagelist = new ArrayList<HashMap<String, String>>();
		JSONArray data = new JSONArray();
		JsonParse js = new JsonParse();
		JSONObject jso = new JSONObject();
		jso = js.getJSONFromUrl(url + page);
		try {
			data = jso.getJSONArray("data");
			for (int i = 0; i < data.length(); i++) {
				JSONObject obj = data.getJSONObject(i);
				String image = obj.getString("images");
				HashMap<String, String> arr = new HashMap<String, String>();
				arr.put("images", image);

				imagelist.add(arr);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return imagelist;
	}

	// Adapter cho Gridview
	public class ImageAdapter extends BaseAdapter {
		private LayoutInflater inflater = null;

		public int getCount() {
			return imageUrls.length;
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}
		public View getView(int position, View convertView, ViewGroup parent) {
			View vi = convertView;
			if (convertView == null) {
				inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				vi = inflater.inflate(R.layout.custom_gv_new, null);
			}
			ImageView imageView = (ImageView) vi.findViewById(R.id.image);
			ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
					getApplicationContext())
					.threadPriority(Thread.NORM_PRIORITY - 2)
					.memoryCacheSize(2 * 1024 * 1024)
					// 2 Mb
					.denyCacheImageMultipleSizesInMemory()
					.discCacheFileNameGenerator(new Md5FileNameGenerator())
					.imageDownloader(
							new ExtendedImageDownloader(getApplicationContext()))
					.tasksProcessingOrder(QueueProcessingType.LIFO)
					.enableLogging() // Not necessary in common
					.build();
			// Initialize ImageLoader with configuration.
			ImageLoader.getInstance().init(config);
			imageLoader.displayImage(imageUrls[position], imageView, options);

			return vi;
		}
	}
}
